package com.fadadianqi.logistics.admin.net;

import java.io.Serializable;
import java.nio.ByteBuffer;

public abstract class Packet implements Serializable {

    /**
     *
     */
    private static final long serialVersionUID = -9011427035633654702L;

    public static final String CHARSET = "utf-8";


    public Packet() {

    }

    public abstract PacketHead getHead();

    public abstract byte[] getBodyBytes();

    public byte[] toBytes() {
        byte[] bytes = null;
        PacketHead head = getHead();
        byte[] bodyBytes = getBodyBytes();
        if (bodyBytes != null) {
            head.setBodyLen(bodyBytes.length);
            byte[] headBytes = head.toBytes();
            int len = bodyBytes.length + headBytes.length;
            ByteBuffer buffer = ByteBuffer.allocate(len);
            buffer.put(headBytes);
            buffer.put(bodyBytes);
            bytes = buffer.array();
        } else {
            head.setBodyLen(0);
            byte[] headBytes = head.toBytes();
            int len = headBytes.length;
            ByteBuffer buffer = ByteBuffer.allocate(len);
            buffer.put(headBytes);
            bytes = buffer.array();
        }
        return bytes;
    }

    public Session getSession() {
        return session;
    }

    public void setSession(Session session) {
        this.session = session;
    }

    private Session session;

}
